package com.edu.servlet;

import com.edu.bean.User;
import com.edu.service.UserPostService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/user/consult")
public class UserConsultListServlet extends HttpServlet {
    private UserPostService postService = new UserPostService();
    private static final int PAGE_SIZE = 10;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 检查登录状态
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/user/login.jsp");
            return;
        }

        // 获取页码参数
        String pageStr = request.getParameter("page");
        int page = 1;
        try {
            if (pageStr != null && !pageStr.trim().isEmpty()) {
                page = Integer.parseInt(pageStr);
                if (page < 1) {
                    page = 1;
                }
            }
        } catch (NumberFormatException e) {
            page = 1;
        }

        // 获取数据
        List<Map<String, Object>> consultList = postService.userGetConsultPosts(user.getUserId(), page, PAGE_SIZE);
        int totalCount = postService.userGetConsultPostsTotalCount(user.getUserId());
        int totalPages = (totalCount + PAGE_SIZE - 1) / PAGE_SIZE;

        // 获取统计数据
        int repliedCount = postService.userGetRepliedConsultCount(user.getUserId());
        int waitingCount = postService.userGetWaitingConsultCount(user.getUserId());

        // 设置属性
        request.setAttribute("consultList", consultList);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("repliedCount", repliedCount);
        request.setAttribute("waitingCount", waitingCount);

        // 转发到列表页
        request.getRequestDispatcher("/user/consult/list.jsp").forward(request, response);
    }
}